var express = require('express');
var router = express.Router();
var Book = require("../../models/book.js");
var chkLogin = require("./filter/rules.js");
//添加
router.get("/book/add",chkLogin);
router.get("/book/add",function(req,res,next){
    res.render("admin/book/add",{
        user: req.session.user
    });
});
router.post("/book/add",chkLogin);
router.post("/book/add",function(req,res,next){
    var _book={};
    for(var i in req.body){
        _book[i]=req.body[i];
    }
    var obj = new Book(_book);
    var _json={};
    obj.save(function(err,book){
        if(err){
            //throw err;
            _json.msg="更新失败";
        }else{
            _json.succeed="succeed";
            _json.msg="更新成功";
        }
        res.send(_json);
    });
});


//列表
router.get("/book/list",chkLogin);
router.get("/book/list",function(req,res,next){
    var _pageSize,
        _page = req.query.page  ? req.query.page : null;
   Book.getTen(_pageSize,_page,function(err,book,totalPage){
      if(err){ throw err;}
      res.render("admin/book/list",{
          book:book,
          totalPage:totalPage,
          page:_page,
          user: req.session.user
      });
   });
});

//编辑
router.get("/book/edit",chkLogin);
router.get("/book/edit",function(req,res,next){
    var _id = req.query.id;
    if(_id){
        var obj = new Book();
        obj.getOne(_id,function(err,book){
            if(err) throw err;
            res.render("admin/book/edit",{
                book:book[0],
                user: req.session.user
             });
        });
    }
});
router.post("/book/edit",chkLogin);
router.post("/book/edit",function(req,res,next){
    var _book={};
    for(var i in req.body){
        _book[i]= req.body[i];
    }
    var obj = new Book(_book);
    var _json={};
    obj.update(function(err,book){
       if(err){throw err;
           _json.msg="更新失败";
       }else{
           _json.msg="更新失败";
           _json.succeed="succeed";
       }
       res.send(_json);
    });
});

//删除
router.get("/book/delete",chkLogin);
router.get("/book/delete",function(req,res,next){
    var _id = req.query.id;
    if(_id){
        var obj = new Book();
        obj.delete(_id,function(err,book){
           if(err){throw  err;}
           res.redirect("/admin/book/list");
        });
    }
});




module.exports = router;